#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

   videoDecode = NULL;
   videoThread = NULL;

    ui->startPushButton->setEnabled(true);
    ui->stopPushButton->setEnabled(false);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_startPushButton_clicked()
{
    QString url = ui->urlLineEdit->text();
    if(url.isEmpty())
    {
        QMessageBox::warning(this,"提示","输入的地址不正确！",QMessageBox::Close);
        return;
    }

    ui->startPushButton->setEnabled(false);
    ui->stopPushButton->setEnabled(true);

    videoDecode = new VideoDecode(this);

   if(videoDecode)
   {
       videoDecode->SetUrl( url );
       //rtsp://127.0.0.1:8554/aabb
       videoDecode->Init();
      
      //绑定信号和槽：解码器解码出图，widget显图
       connect(videoDecode, SIGNAL(GetImage(QImage)), this, SLOT(SetImage(QImage)));

       //start a new thread , to run decoding(rtsp)
       videoThread = new VideoThread(this);
       if(videoThread)
       {
           videoThread->setFFmpeg(videoDecode);
           videoThread->start();
        }
   }
}

void Widget::on_stopPushButton_clicked()
{
   if(videoDecode)
   {
       videoDecode->setStopped(1);  /// stop camera
   }

   QThread::msleep(500);// sleep(...), msleep(...)

   if(videoDecode)
   {
       videoDecode->Deinit();
       delete videoDecode;
       videoDecode = NULL;
   }

   if(videoThread)
   {
       delete videoThread;
       videoThread = NULL;
   }

    ui->startPushButton->setEnabled(true);
    ui->stopPushButton->setEnabled(false);
}

void Widget::SetImage(const QImage &image)
{
    int tempWidth = ui->videoLabel->geometry().width();
    int tempHeight = ui->videoLabel->geometry().height();
    if (image.height() > 0)
    {
        QPixmap pix = QPixmap::fromImage(image.scaled(tempWidth, tempHeight));
        ui->videoLabel->setPixmap(pix);
    }
}

